<template>
  <div class="app-container">
    <el-button :icon="ArrowLeft" @click="$router.go(-1)" class="no-background-button"></el-button>

    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-item" @click="createNewConversation">
        <img src="@/assets/icons/svg/新对话.svg" alt="创建新对话" class="sidebar-icon" />
        <span class="tooltip">创建新对话</span>
      </div>
      <div class="sidebar-item" @click="viewRecentConversations">
        <img src="@/assets/icons/svg/历史记录.svg" alt="查看历史对话" class="sidebar-icon" />
        <span class="tooltip">查看历史对话</span>
      </div>
    </div>

    <!--    <div v-if="aiTitle" class="ai-title">{{ aiTitle }}</div>-->

    <!-- 聊天窗口 -->
    <div class="chat-container">

      <div class="chat-window">
        <div class="message-list" ref="chatContainer">
          <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
            <!-- AI 消息显示头像和文字框 -->
            <div v-if="msg.role === 'assistant'" class="assistant-message">
              <img src="/images/AI.png" alt="AI Avatar" class="avatar" />
              <div class="bubble">
                {{ msg.text }}
              </div>
              <div class="actions">
                <button @click="copyResponse(msg.text)" class="action-button copy-button">
                  <el-icon class="button-icon">
                    <CopyDocument />
                  </el-icon>
                  复制
                </button>
                <button @click="regenerateResponse(index)" class="action-button regenerate-button">
                  <el-icon class="button-icon">
                    <Refresh />
                  </el-icon>
                  重新生成
                </button>
              </div>
            </div>
            <!-- 用户消息只显示文字框 -->
            <div v-else class="bubble user-bubble">{{ msg.text }}</div>
          </div>
          <div v-if="loading" class="loading-indicator">AI 正在思考...</div>
        </div>

        <div class="input-area">
          <el-input v-model="inputMessage" type="textarea" :rows="1" placeholder="输入你的问题..." @keyup.enter="handleSend"
            class="chat-input" />
          <el-button type="primary" @click="handleSend" :loading="loading" class="send-button">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import { Refresh, CopyDocument, ArrowLeft, } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import useUserStore from "@/store/modules/user";
import { ChatWebSocket } from "@/utils/chatWebSocket";
import axios from "axios"; // 引入 axios
// import { getAiConversationId, addAiConversation } from "../../api/aiConversation/aiConversation";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const aiTitle = ref('');
const messages = ref([]); // 初始化为空数组
const inputMessage = ref('');
const loading = ref(false);
const chatContainer = ref(null);
const socket = ref(null);
const userId = ref(userStore.userId || localStorage.getItem('userId'));
const currentConversationId = ref(localStorage.getItem('currentConversationId'));

// 检查是否是从最近对话列表进入
const isFromRecent = ref(route.query.fromRecent === 'true');

// 获取或清除对话ID
if (isFromRecent.value) {
  // 如果是从最近对话进入，使用保存的对话ID
  currentConversationId.value = localStorage.getItem('currentConversationId');
} else {
  // 如果是从主页进入，清除之前的对话状态
  localStorage.removeItem('currentConversationId');
  localStorage.removeItem('messages');
  currentConversationId.value = null;
  messages.value = [];
}

// 检查并确保 userId 存在
const ensureUserId = () => {
  if (!userId.value) {
    // 尝试从 store 重新获取
    userId.value = userStore.id;
    console.log('userId:', userId.value);
    console.log('userStore.userId:', userStore.id);
    // 如果还是没有，尝试从 localStorage 获取
    if (!userId.value) {
      userId.value = localStorage.getItem('userId');
    }

    // 如果仍然没有，显示错误并返回 false
    if (!userId.value) {
      ElMessage.error('用户未登录或 ID 无效');
      return false;
    }
  }
  return true;
};

// 添加连接状态检查
const isConnected = ref(false);
const connectionAttempts = ref(0);
const maxAttempts = 3;

// 修改 WebSocket 连接逻辑
const connectWebSocket = () => {
  if (!ensureUserId()) {
    return;
  }

  if (socket.value && isConnected.value) {
    console.log("WebSocket 已连接，跳过重连");
    return;
  }

  if (socket.value) {
    socket.value.close();
    socket.value = null;
  }

  // 构建 WebSocket URL
  let wsUrl = `ws://localhost:8080/ws?userId=${userId.value}`;
  if (isFromRecent.value && currentConversationId.value) {
    wsUrl += `&conversationId=${currentConversationId.value}`;
  }

  console.log('正在连接到 WebSocket，URL:', wsUrl);
  console.log('当前用户ID:', userId.value);
  console.log('当前对话ID:', currentConversationId.value);
  console.log('是否来自最近对话:', isFromRecent.value);

  socket.value = new ChatWebSocket(
    wsUrl,
    (data) => {
      console.log('收到WebSocket消息:', data);
      try {
        const parsedData = typeof data === 'string' ? JSON.parse(data) : data;
        if (parsedData?.message) {
          const newMessage = { role: "assistant", text: parsedData.message };
          messages.value.push(newMessage);
          localStorage.setItem('messages', JSON.stringify(messages.value));
          loading.value = false;
          nextTick(() => {
            scrollToBottom();
          });
        }
      } catch (error) {
        console.error('处理WebSocket消息时出错:', error);
      }
    },
    () => {
      console.log("WebSocket 连接已建立");
      isConnected.value = true;
      connectionAttempts.value = 0;
    },
    (event = {}) => {
      const closeCode = event.code || 0;
      console.log("WebSocket 连接关闭，状态码:", closeCode);
      isConnected.value = false;

      if (closeCode === 1000) {
        console.log("WebSocket 正常关闭");
      } else if (closeCode === 1006 || closeCode === 0) {
        console.log("WebSocket 异常关闭，尝试重连");
        if (connectionAttempts.value < maxAttempts) {
          connectionAttempts.value++;
          console.log(`第 ${connectionAttempts.value} 次重试连接...`);
          setTimeout(() => {
            connectWebSocket();
          }, 3000);
        } else {
          console.log("达到最大重试次数");
          ElMessage.error("连接失败，请刷新页面重试");
        }
      }
    },
    (error) => {
      console.error("WebSocket 错误:", error);
      isConnected.value = false;
      ElMessage.error("WebSocket 发生错误");
    }
  );

  try {
    socket.value.connect();
  } catch (error) {
    console.error("连接 WebSocket 时发生错误:", error);
    isConnected.value = false;
    ElMessage.error("连接失败，请刷新页面重试");
  }
};

// 修改发送消息的方法
const handleSend = async (event) => {
  // 阻止回车键的默认行为
  if (event?.type === 'keyup') {
    event.preventDefault();
  }

  // 使用输入框的值作为消息内容
  const message = inputMessage.value.trim();
  if (!message) {
    return;
  }

  try {
    await sendMessage(message);
    // 发送成功后清空输入框
    inputMessage.value = '';
  } catch (error) {
    console.error('发送失败:', error);
  }
};

const sendMessage = async (messageContent) => {
  const message = String(messageContent?.text || messageContent || '');

  if (!message.trim()) {
    console.log('消息内容为空，不发送');
    return;
  }

  // 如果未连接，尝试重新连接
  if (!isConnected.value) {
    console.log('WebSocket 未连接，尝试重新连接...');
    connectWebSocket();
    // 等待连接建立
    await new Promise((resolve) => setTimeout(resolve, 1000));
    if (!isConnected.value) {
      ElMessage.error('无法建立连接，请刷新页面重试');
      return;
    }
  }

  try {
    loading.value = true;
    const newMessage = { role: 'user', text: message };
    messages.value.push(newMessage);
    localStorage.setItem('messages', JSON.stringify(messages.value));

    if (socket.value && isConnected.value) {
      const messageData = {
        message: message,
        userId: userId.value,
        conversationId: currentConversationId.value
      };

      console.log('发送消息:', messageData);
      socket.value.sendMessage(JSON.stringify(messageData));

      nextTick(() => {
        scrollToBottom();
      });
    } else {
      throw new Error('WebSocket 未连接');
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败，请检查网络连接');
    loading.value = false;
  }
};

const regenerateResponse = async (index) => {
  loading.value = true;
  const question = messages.value[index - 1]?.text;
  if (!question) {
    messages.value.push({ role: "assistant", text: "无法重新生成，请尝试重新提问。" });
    loading.value = false;
    return;
  }
  socket.value.sendMessage(question);

  // 保存到 localStorage
  localStorage.setItem("messages", JSON.stringify(messages.value));
};

const copyResponse = async (text) => {
  await navigator.clipboard.writeText(text);
  ElMessage.success("内容已复制到剪贴板！");
};

const scrollToBottom = () => {
  nextTick(() => {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
  });
};

// 创建新的 AI 对话
function createNewConversation() {
  const aiConversation = {
    userId: userId.value
  };
  if (socket.value) socket.value.close();
  socket.value.connect();
  // 如果接口调用成功，更新 messages 数组
  messages.value = [{ role: "assistant", text: "你好，我是智文助手。" }];
  localStorage.setItem("messages", JSON.stringify(messages.value));
};

const viewRecentConversations = () => {
  router.push("/front/recent-conversations");
};

// const aiConversationId = ref('');
//
// function findAiConversationId(){
//   getAiConversationId().then(res => {
//     if (res.code === 200) {
//       ElMessage.success(res.msg);
//     } else {
//       ElMessage.error(res.msg);
//     }
//   })
// };
//
// const fetchAITitle = async () => {
//   try {
//     const response = await axios.get('http://localhost:8080/aiConversation/aiConversation/title', aiConversationId);
//     // console.log(response.data.title);
//     aiTitle.value = response.data.title;
//     // console.log(aiTitle.value)
//   } catch (error) {
//     console.error('获取AI对话名称失败', error);
//   }
// };
//
//
// // 使用created生命周期钩子调用获取AI对话名称的方法
// onMounted(() => {
//   findAiConversationId();
//   fetchAITitle();
// });

onMounted(() => {
  if (isFromRecent.value) {
    // 如果是从最近对话进入，加载保存的消息
    const storedMessages = localStorage.getItem('messages');
    if (storedMessages) {
      messages.value = JSON.parse(storedMessages);
    }
  } else {
    // 如果是新对话，显示默认欢迎消息
    messages.value = [
      {
        role: "assistant",
        text: "您好！我是智文助手，很高兴为您服务"
      }
    ];
  }

  // 确保在挂载时有有效的 userId
  if (ensureUserId()) {
    connectWebSocket();
  } else {
    ElMessage.error("请先登录");
  }
});

onBeforeUnmount(() => {
  if (socket.value) socket.value.close();
});
</script>

<style scoped>
/* 侧边栏样式 */
.app-container {
  display: flex;
  height: 100vh;
  background: linear-gradient(135deg, #f0f8ff, #e0e7ff);
}

.no-background-button {
  background: none !important;
  /* 去掉背景 */
  border: none !important;
  /* 去掉边框 */
  padding: 0;
  /* 去掉内边距 */
  color: #1976d2;
  /* 设置箭头颜色为深蓝色 */
  font-size: 26px;
  /* 调整箭头大小 */
  cursor: pointer;
  /* 鼠标悬停时显示手型 */

}

.no-background-button:hover {
  color: #0056b3;
  /* 鼠标悬停时箭头颜色更深 */
}

.sidebar {
  width: 60px;
  /* 缩小侧边栏宽度 */
  background: rgba(255, 255, 255, 0.5);
  /* 设置背景透明，增加透明度 */
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  /* 垂直居中 */
  padding: 10px;
  height: 14vh;
  /* 控制侧边栏的高度，减少高度 */
  position: absolute;
  /* 绝对定位 */
  top: 30vh;
  /* 距离顶部 30% 的位置 */
  border-radius: 10px;
  /* 设置圆角 */
}

.sidebar-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 3px 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  position: relative;
  border-radius: 10px;
  /* 设置圆角 */
}

.sidebar-item:hover {
  background-color: rgba(0, 0, 0, 0.2);
  /* 深色背景 */
}

.sidebar-icon {
  width: 24px;
  /* 缩小图标大小 */
  height: 24px;
  margin: 10px 0;
  /* 增加图标之间的间距 */
}

.tooltip {
  position: absolute;
  left: 50px;
  /* 弹出文字的位置 */
  background: black;
  /* 黑色背景 */
  color: white;
  padding: 6px 8px;
  /* 减小文字框的内边距 */
  border-radius: 3px;
  /* 减小圆角 */
  font-size: 12px;
  /* 减小文字大小 */
  white-space: nowrap;
  opacity: 0;
  /* 默认不显示 */
  transition: opacity 0.3s ease;
  pointer-events: none;
  /* 防止鼠标与提示框交互 */
}

.sidebar-item:hover .tooltip {
  opacity: 1;
  /* 鼠标悬浮时显示 */
}

/* 聊天窗口样式 */
.chat-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.chat-window {
  width: 100%;
  max-width: 800px;
  height: 80vh;
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  background: #ffffff;
  overflow: hidden;
  transition: all 0.3s ease-in-out;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f9f9f9;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  display: flex;
  margin-bottom: 15px;
  transition: all 0.3s ease-in-out;
}

.message.user {
  justify-content: flex-end;
}

.message.assistant {
  justify-content: flex-start;
}

.assistant-message {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  position: relative;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 25px;
}

.bubble {
  max-width: 90%;
  padding: 16px;
  border-radius: 20px;
  font-size: 16px;
  line-height: 1.5;
  position: relative;
  transition: all 0.3s ease-in-out;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
  word-wrap: break-word;
  white-space: normal;
  background: #e0e7ff;
  color: #333;
  text-align: left;
  /* 确保文字左对齐 */
}

.user-bubble {
  background: #6366f1;
  color: white;
  text-align: left;
  /* 确保文字左对齐 */
  border-bottom-right-radius: 0;
}

.actions {
  position: absolute;
  bottom: -30px;
  right: 0;
  display: flex;
  gap: 0px;
}

.action-button {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  background: #f5f5f5;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  color: #666;
  cursor: pointer;
  transition: background-color 0.3s ease;
  white-space: nowrap;
}

.action-button:hover {
  background: #e0e0e0;
}

.action-button:active {
  background: #dcdcdc;
}

.button-icon {
  font-size: 14px;
  color: #666;
}

.input-area {
  display: flex;
  padding: 28px 35px;  /* 增加内边距 */
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  gap: 18px;  /* 增加间距 */
  border-radius: 0 0 24px 24px;  /* 底部圆角 */
}

/* 输入框样式 */
.chat-input {
  flex: 1;
  background: rgba(255, 255, 255, 0.9) !important;
  border: 2px solid rgba(99, 102, 241, 0.1) !important;
  border-radius: 24px !important;  /* 增加圆角 */
  transition: all 0.3s ease !important;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06) !important;
}

.chat-input:hover {
  border-color: rgba(99, 102, 241, 0.3) !important;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1) !important;
  transform: translateY(-1px);
}

.chat-input:focus {
  border-color: rgba(99, 102, 241, 0.5) !important;
  box-shadow: 0 8px 24px rgba(99, 102, 241, 0.15) !important;
}

/* 输入框内的文本区域样式 */
.chat-input :deep(.el-textarea__inner) {
  padding: 16px 24px !important;  /* 增加内边距 */
  font-size: 15px !important;
  line-height: 1.6 !important;
  color: #333 !important;
  resize: none !important;
  border: none !important;
  background: transparent !important;
  border-radius: 24px !important;  /* 文本区域也要圆角 */
}

/* 发送按钮样式 */
.send-button {
  min-width: 100px;  /* 减小最小宽度 */
  height: 55px !important;  /* 减小高度 */
  font-size: 17px;  /* 稍微减小字体 */
  font-weight: 500;
  letter-spacing: 0.5px;
  background: linear-gradient(135deg, #6366f1, #4f46e5) !important;
  border: none;
  border-radius: 22px !important;  /* 调整圆角以匹配新高度 */
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.2);
  transition: all 0.3s ease;
  padding: 0 20px;  /* 调整内边距 */
}

.send-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(99, 102, 241, 0.3);
  background: linear-gradient(135deg, #5558ee, #4338e0) !important;
}

.send-button:active {
  transform: translateY(0);
}

.send-button:disabled {
  background: linear-gradient(135deg, #c7c8f3, #b6b4e6) !important;
  cursor: not-allowed;
  transform: none;
}

.loading-indicator {
  font-style: italic;
  color: #6366f1;
  text-align: center;
  padding: 15px;
}
</style>